Page({
  data: {
    technicians: [],
    latitude: '',
    longitude: '',
    page: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false
  },

  onLoad: function(options) {
    // 获取当前位置并加载附近技师
    this.getLocationAndLoadTechnicians();
  },

  getLocationAndLoadTechnicians: function() {
    const that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        that.loadNearbyTechnicians();
      },
      fail: function() {
        wx.showToast({
          title: '获取位置失败，请检查定位权限',
          icon: 'none'
        });
      }
    });
  },

  loadNearbyTechnicians: function() {
    if (this.data.isLoading || !this.data.hasMore) return;
    
    this.setData({ isLoading: true });
    
    const app = getApp();
    app.request({
      url: '/accounts/location/nearby/',
      method: 'GET',
      data: {
        latitude: this.data.latitude,
        longitude: this.data.longitude,
        page: this.data.page,
        page_size: this.data.pageSize
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const newTechnicians = res.data.results || res.data;
          const technicians = this.data.page === 1 ? newTechnicians : [...this.data.technicians, ...newTechnicians];
          
          this.setData({
            technicians: technicians,
            hasMore: newTechnicians.length === this.data.pageSize,
            page: this.data.page + 1,
            isLoading: false
          });
        } else {
          wx.showToast({
            title: '获取技师列表失败',
            icon: 'none'
          });
          this.setData({ isLoading: false });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        this.setData({ isLoading: false });
      }
    });
  },

  onReachBottom: function() {
    // 页面上拉触底事件的处理函数
    if (this.data.hasMore) {
      this.loadNearbyTechnicians();
    }
  },

  goToTechnicianDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/customer/technicianDetail?id=${id}`
    });
  },

  onPullDownRefresh: function() {
    // 下拉刷新
    this.setData({
      page: 1,
      hasMore: true
    });
    this.getLocationAndLoadTechnicians();
    wx.stopPullDownRefresh();
  }
});